<template>
  <tl-sub-page :render="render" :with-header="false" :visible.sync="visible" v-dialogDrag :title="title" :close-on-click-modal="false" class="tl-drawer" :size="size" @open="open" @close="close" :destroy-on-close="true" :modal-append-to-body="true" :close-on-press-escape="false" :append-to-body="true">
    <div class="project-container">
      <div class="customer-header">
        <div class="info">
          <img src="/static/images/paojectManager/mpm_plan_edit.png" class="logo" style="width: 55px;height: 55px" />
          <div class="content" :title="projectinfo.projectname">
            <p>
              <b style="overflow:hidden;text-overflow:ellipsis;white-space:nowrap;width: 52%;">{{ model.projectname }}</b>
            </p>
            <p class="light">
              <span>项目经理：{{ projectinfo.projectmanager }}</span>
              <span>创建时间：{{ formatDate(model.createon) }}</span>
            </p>
          </div>
        </div>
        <!-- <div class="toolbar" style="margin-top: 10px;">
          <el-button type="danger" size="small" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
        </div> -->
        <div class="toolbar" style="float:right;margin-bottom:6px">
          <el-button type="danger" size="small" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
        </div>
      </div>
      <div class="project-nav" :style="{ height: mainHeight + 'px' }">
        <ul class="nav-list" style="top:0px">
          <template v-for="(item, index) in navList">
            <li :key="item.code" v-if="model.id || item.show || index === 0" :class="item.on ? 'on' : ''" @click="clickNav(item.code)" style="cursor: pointer;clear: both">
              <span style="float: left;width: 100px">{{ item.name }}</span>
              <span style="float: left;">
                <i v-if="item.count > 0">{{ item.count }}</i>
                <label v-if="item.flag">{{ item.flag }}</label>
              </span>
            </li>
          </template>
        </ul>
      </div>
      <!-- <el-row v-if="fromApproval === '1'">
      <el-col :span="24">
        <el-button type="danger" style="float: right" size="small" icon="el-icon-close" circle @click="doCancelEdit"></el-button>
      </el-col>
    </el-row> -->
      <div class="project-main" :style="{ height: mainHeight + 'px' }">
        <el-scrollbar class="customer-main-container" id="customerMainContainer">
          <div style="padding:0 10px">
            <a id="baseinfo" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                基本信息
              </div>
              <el-form class="tl-form" ref="form" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="变更原因" prop="changereason" v-if="displayChangeReasonFlag" :rules="rules.validateRequire">
                      <el-input type="textarea" show-word-limit maxlength="1000" :rows="4" v-model="model.changereason"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="策划书名称" prop="proposalname" :rules="rules.validateRequire">
                      <el-input v-model="model.proposalname" :disabled="true"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <!-- <el-row>
                  <el-col :span="24">
                    <el-form-item label="策划书描述" prop="plandescription" :rules="rules.validateRequire">
                      <el-input v-model="model.plandescription" type="textarea" :rows="4" maxlength="800" show-word-limit></el-input>
                    </el-form-item>
                  </el-col>
                </el-row> -->
              </el-form>
            </div>
            <a id="background" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                背景策略
              </div>
              <el-form class="tl-form" ref="form1" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目背景" prop="projectbackground" :rules="rules.validateRequire">
                      <el-input v-model="model.projectbackground" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请简要陈述项目背景，最多1000字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目目标" prop="projecttarget" :rules="rules.validateRequire">
                      <el-input v-model="model.projecttarget" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请简要陈述目标，最多1000字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <a id="implementation" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                项目实施方案
              </div>
              <el-form class="tl-form" ref="form2" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
                <el-row>
                  <el-col :span="24">
                    <el-form-item label="项目实施方案" prop="projectimplementation" :rules="rules.validateRequire">
                      <el-input v-model="model.projectimplementation" type="textarea" :rows="4" maxlength="1000" show-word-limit placeholder="请简要陈述项目实施方案，最多1000字。"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </div>
            <a id="milepost" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                里程碑
              </div>
              <el-form class="tl-form" style="margin-top:20px" ref="form5" :model="model" :rules="rules" label-width="150px">
                <tl-line ref="line" :parentId="model.id" :editable="!disableSave" :isshowdisable="disableEditSubmit || disableSave" :projectinfo="projectinfo" :planstate="model.state"></tl-line>
              </el-form>
            </div>
            <a id="docapplyinfo" class="step-position">&nbsp;</a>
            <div>
              <div class="tl-form-line-title">
                单据信息
              </div>
              <el-form class="tl-form" ref="form6" :model="model" :rules="rules" label-width="150px" :disabled="disableEditSubmit || disableSave">
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="申请部门" prop="applydeptname">
                      <tl-ref-dept v-model="model.applydeptcode" :initDisplayData.sync="model.applydeptname" :disabled="true" dataType="code" nameType="fullname" :singleSelect="true" :externalQueryParam="{ qry_enabled: 1 }"></tl-ref-dept>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="申请公司" prop="applyorgname">
                      <el-input v-model="model.applyorgname" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="申请人姓名" prop="applyusername">
                      <tl-ref-user v-model="model.applyusername" :initDisplayData.sync="model.applyusername" :disabled="true" dataType="code" :singleSelect="true"></tl-ref-user>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="申请人工号" prop="applyusercode">
                      <el-input v-model="model.applyusercode" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="单据日期" prop="docdate">
                      <el-date-picker v-model="model.docdate" type="date" placeholder="单据日期" value-format="yyyy-MM-dd"></el-date-picker>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="提交时间" prop="submitdate">
                      <el-date-picker v-model="model.submitdate" type="date" placeholder="提交时间" value-format="yyyy-MM-dd" disabled></el-date-picker>
                    </el-form-item>
                  </el-col>
                </el-row>
                <el-row>
                  <el-col :span="12">
                    <el-form-item label="审批流程" prop="flowid">
                      <el-input v-model="model.dispflowid" :readonly="true" class="is-disabled"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="12">
                    <el-form-item label="状态" prop="state">
                      <el-input v-model="model.dispstate" disabled></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
              <div slot="footer" class="dialog-footer" style="float:right;margin-top:10px">
                <el-button @click="doSavePlan" :loading="saveLoading" v-if="!disableEditSubmit" :disabled="disableSave" icon="el-icon-document-checked" type="primary">保存</el-button>
                <el-button @click="doSubmitApproval" :loading="submitLoading" v-if="!disableEditSubmit" :disabled="disableApproval" type="primary"> <svg-icon icon-class="send" />提交审批 </el-button>
                <tl-attachment ref="attachmentRef" sourceType="GpmProjectPlan" :sourceId="model.id" :disabled="disableAttachment" :editable="stateEdit">
                  <el-button type="primary" :disabled="disableAttachment" icon="el-icon-paperclip" @click="$refs.attachmentRef.openUploadDialog()">{{ this.$refs.attachmentRef ? this.$refs.attachmentRef.btnTitle : '' }} [{{ this.$refs.attachmentRef ? (this.$refs.attachmentRef.fileList.length > 0 ? this.$refs.attachmentRef.fileList.length : this.$refs.attachmentRef.fileCount) : 0 }}] </el-button>
                </tl-attachment>
                <el-button type="primary" @click.native="openChangeHistoryDialog('historyList')" v-if="model.id && model.version > 1">修改历史</el-button>
                <el-button @click="$refs.history.visible = true" :disabled="disableApprovalHistory" type="primary"> <svg-icon icon-class="list" />审批历史 </el-button>
            </div>
            </div>
            <tl-approval-history ref="history" sourceType="GpmProjectPlan" :sourceId="model.id" />
          </div>
        </el-scrollbar>
      </div>
    </div>
    <change-log-history ref="historyList" topSourceType="GpmProjectPlan" :topSourceId="model.id + ''"></change-log-history>
  </tl-sub-page>
</template>

<script>
/** mixins */
import { mixin_approval_edit } from "@tapui/mixins/mixin_approval_edit"
/** 子组件 */
import tlLine from '../gpmProjectMilepost/indexFrame'
import changeLogHistory from '../gpmProject/component/changeLogHistory'
/** 工具类 */
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { formatDate } from '@tapui/utils/date'
/** VUE配置 */
export default {
  mixins: [mixin_approval_edit],
  components: { tlLine, changeLogHistory },
  data() {
    return {
      moduleTitle: '项目策划',
      urlPrefix: '/sd/projectPlan/',
      url: {
        // 额外的url
      },
      activeTabName: 'basic',
      isRefreshLine: false,
      count: 0,
      planInfo: {},
      navList: [{ name: '基本信息', count: 0, flag: null, on: true, code: 'baseinfo', show: true }, { name: '背景策略', count: 0, flag: null, on: true, code: 'background', show: true }, { name: '项目实施方案', count: 0, flag: null, on: true, code: 'implementation', show: true }, { name: '里程碑', count: 0, flag: null, on: true, code: 'milepost', show: true }, { name: '单据信息', count: 0, flag: null, on: true, code: 'docapplyinfo', show: true }],
      fromApproval: '',
      size: '95%',
      mainHeight: 100,
      displayChangeReasonFlag: false
    }
  },
  props: {
    render: {
      default: 'el-drawer',
      type: String
    },
    projectinfo: {},
    oldmilepost: []
  },
  methods: {
    formatDate(date) {
      return formatDate(new Date(date), 'yyyy-MM-dd HH:mm')
    },
    // 点击左侧导航
    clickNav(code) {
      this.navList.forEach((m) => {
        if (m.code === code) {
          m.on = true
        } else {
          m.on = false
        }
      })
      let element = document.getElementById(code)
      if (element === null) return
      let goY = element.getBoundingClientRect().y - 75
      this.mainScrollElement.scrollTop += goY
    },
    resizeHandler() {
      this.mainHeight = document.body.getBoundingClientRect().height - 100
    },
    /** 页面滚动时，动态改变左侧导航选中的元素，抽屉组件必有 **/
    onMainScroll() {
      const scrollFun = () => {
        const currentEl = [...this.$el.getElementsByClassName('step-position')].find((item) => item.getBoundingClientRect().y >= 0)
        const code = currentEl ? currentEl.id : ''
        this.navList.forEach((m) => (m.on = m.code === code))
      }
      this.mainScrollElement.removeEventListener('scroll', scrollFun)
      this.mainScrollElement.addEventListener('scroll', scrollFun)
    },
    assignDefaultValue() {
      if (this.isAdd) {
        this.$set(this.model, 'projectid', this.projectinfo.id)
        this.$set(this.model, 'deptcode', this.projectinfo.deptcode)
        this.$set(this.model, 'deptcommoncode1', this.projectinfo.deptcommoncode1)
        this.$set(this.model, 'proposalname', this.projectinfo.projectname + '策划书')
        this.$set(this.model, 'projectcode', this.projectinfo.projectcode)
        this.$set(this.model, 'projectname', this.projectinfo.projectname)
        this.$set(this.model, 'applyorgcode', this.org.code)
        this.$set(this.model, 'applyorgname', this.org.name)
        this.$set(this.model, 'applydeptcode', this.dept.code)
        this.$set(this.model, 'applydeptname', this.dept.fullname)
        this.$set(this.model, 'applyusercode', this.user.code)
        this.$set(this.model, 'applyusername', this.user.name)
        this.$set(this.model, 'usercode', this.user.code)
        this.$set(this.model, 'username', this.user.name)
        this.$set(this.model, 'docdate', new Date())
        this.$set(this.model, 'deptcode', this.projectinfo.deptcode)
      }
    },
    checkplancount() {
      let param = {}
      if (this.isAdd) {
        param = {
          projectcode: this.projectinfo.projectcode,
          isadd: this.isAdd
        }
      } else {
        param = {
          projectcode: this.projectinfo.projectcode,
          isadd: this.isAdd,
          id: this.model.id
        }
      }
      getAction('/sd/projectPlan/checkplancount', param).then((res) => {
        if (res.success) {
          this.displayChangeReasonFlag = !res.result.isFirstPlan
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    open() {
      this.navList.forEach(function(item, index) {
        if (index === 0) {
          item.on = true
        } else {
          item.on = false
        }
      })
      this.model = {}
      this.resizeHandler()
      this.$nextTick(() => {
        if (this.isAdd === true) {
          this.title = '新增' + this.moduleTitle
          // 需要添加重复判断
          if (this.$store.getters.param.isAvoidRepeat === true) {
            this.queryBillUid()
          }
          // this.loadData()
          if (this.isQueryInitData === true) {
            // 后台进行数据初始化
            this.queryInitData().then((_) => {
              this.assignDefaultValue()
              this.loaded()
              this.addDefaultValue()
              // this.doAdd()
            })
          } else {
            // 前台进行数据初始化
            this.$set(this.model, 'enabled', 1)
            this.$set(this.model, 'sortcode', 0)
            this.assignDefaultValue()
            this.loaded()
            this.addDefaultValue()
            // this.doAdd()
          }
        } else if (this.disableEditSubmit === false) {
          this.title = '编辑' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
            this.$refs.line.milepostLoadInfo()
          })
        } else {
          this.title = '查看' + this.moduleTitle
          this.queryData(this.id).then((_) => {
            this.loaded()
            this.$refs.line.milepostLoadInfo()
          })
        }
      })
      this.$nextTick(() => {
        this.mainScrollElement = this.$el.querySelector('#customerMainContainer .el-scrollbar__wrap')
        this.onMainScroll()
      })
    },
    close() {
      this.$emit('refresh')
      this.displayChangeReasonFlag = false
      this.model = {}
    },
    loaded() {
      // 页面加载完毕执行
      this.activeTabName = 'basic'
      this.isRefreshLine = false
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
        this.$refs.form1.clearValidate()
        this.$refs.form2.clearValidate()
      })
      this.$refs.line.milepostList = []
      // this.$refs.line.loadData()
      this.checkplancount()
    },
    // 同步项目立项相同字段 并保存
    addDefaultValue() {
      const { projectcode } = this.model
      const param = {
        qry_projectcode: projectcode,
        qry_enabled: 1,
        qry_state: 9,
        sidx: 'createon',
        sord: 'desc',
        pageSize: 10,
        currentPage: 1
      }
      getAction('/sd/projectPlan/list', param).then((res) => {
        if (res.success) {
          if (res.result.dataList.length !== 0) {
            // this.$set(this.model, "plandescription", res.result.dataList[0].plandescription)
            this.$set(this.model, 'projectbackground', res.result.dataList[0].projectbackground)
            this.$set(this.model, 'projecttarget', res.result.dataList[0].projecttarget)
            this.$set(this.model, 'projectimplementation', res.result.dataList[0].projectimplementation)
            var a = res.result.dataList[0].proposalcode
            if (a.length <= 10) {
              this.$set(this.model, 'proposalcode', a + '-2')
            } else {
              let b = parseInt(a.substring(a.lastIndexOf('-') + 1)) + 1
              this.$set(this.model, 'proposalcode', a.substring(0, a.lastIndexOf('-') + 1) + b)
            }
          } else {
            this.$set(this.model, 'projectbackground', this.projectinfo.background)
            this.$set(this.model, 'projecttarget', this.projectinfo.target)
          }
          // 临时字段 用来同步初始里程碑
          this.$set(this.model, 'firstAdd', 1)
          // 保存策划书
          this.doAdd()
          // 同步里程碑
          this.$nextTick((_) => {
            this.$refs.line.updateInfo()
          })
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    queryData(id) {
      if (!this.url.load) {
        this.$tap.alert('请设置load地址!', 'warning')
        return
      }
      let firstAdd = this.model.firstAdd
      return getAction(this.url.load, { id: id }).then((res) => {
        if (res.success) {
          this.model = res.result
          this.model.firstAdd = firstAdd
          if (this.model.firstAdd === 1) {
            this.afterSubmitQueryData()
          }
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    afterSubmitQueryData() {
      this.insertBatch()
    },
    // 同步旧策划书 里程碑,为初始策划书添加默认标前引导里程碑
    insertBatch() {
      // 新增的标记firstAdd，新增的第一次保存firstAdd值为1
      if (this.model.firstAdd === 1) {
        var datamap = {
          oldmilepost: this.oldmilepost,
          projectcode: this.projectinfo.projectcode,
          projectlevel: this.projectinfo.projectlevel,
          planid: this.model.id
        }
        postAction('sd/projectMilepost/insertBatch', datamap).then((res) => {
          if (res.success) {
            this.$refs.line.milepostLoadInfo()
            this.model.firstAdd = 0
          } else {
            this.$tap.alert(res.message, 'warning')
          }
        })
      }
      this.$nextTick(() => {
        this.$refs.line.updateInfo()
        this.$refs.form.clearValidate()
        this.$refs.form1.clearValidate()
        this.$refs.form2.clearValidate()
      })
    },
    doSavePlan() {
      if (this.isAdd) {
        this.doAdd()
      } else {
        this.doEdit()
      }
    },
    beforeApproval() {
      // if (this.$refs.attachmentRef.fileCount === 0 && this.$refs.attachmentRef.fileList.length === 0) {
      //   this.$tap.alert('请上传策划书附件！', 'warning')
      //   this.submitLoading = false
      //   return false
      // }
      // if (this.displayChangeReasonFlag && (this.model.changecontent === undefined || this.model.changecontent === null || this.model.changecontent === '')) {
      //   this.$tap.alert("请填写变更内容！", "warning")
      //   this.submitLoading = false
      //   return false
      // }
      if (this.displayChangeReasonFlag && (this.model.changereason === undefined || this.model.changereason === null || this.model.changereason === '')) {
        this.$tap.alert('请填写变更原因！', 'warning')
        this.submitLoading = false
        return false
      }
      if (this.model.projectbackground === undefined || this.model.projectbackground === null || this.model.projectbackground === '') {
        this.$tap.alert('请填加项目背景！', 'warning')
        this.submitLoading = false
        return false
      }
      if (this.model.projecttarget === undefined || this.model.projecttarget === null || this.model.projecttarget === '') {
        this.$tap.alert('请填加项目目标！', 'warning')
        this.submitLoading = false
        return false
      }
      if (this.model.projectimplementation === undefined || this.model.projectimplementation === null || this.model.projectimplementation === '') {
        this.$tap.alert('请填加项目实施方案！', 'warning')
        this.submitLoading = false
        return false
      }
      if (this.$refs.line) {
        for (let i = 0; i < this.$refs.line.milepostList.length; i++) {
          let milepost = this.$refs.line.milepostList[i]
          if (milepost.milepostname === null || milepost.milepostname === undefined || milepost.planfinishtime === null || milepost.planfinishtime === undefined || milepost.responsible === null || milepost.responsible === undefined) {
            this.$tap.alert('请完善里程碑信息！', 'warning')
            this.submitLoading = false
            return false
          }
        }
        for (let i = 0; i < this.$refs.line.$refs.task.length; i++) {
          if (this.$refs.line.$refs.task[i] && this.$refs.line.$refs.task[i].datas && this.$refs.line.$refs.task[i].datas.length > 0) {
            let task = this.$refs.line.$refs.task[i]
            let tasks = task.datas
            for (let j = 0; j < tasks.length; j++) {
              if (tasks[j].responsible === null || tasks[j].responsible === undefined || tasks[j].planstartdate === null || tasks[j].planstartdate === undefined || tasks[j].planenddate === null || tasks[j].planenddate === undefined) {
                this.$tap.alert('请填写任务信息！', 'warning')
                this.submitLoading = false
                return false
              }
            }
          }
        }
      }
      this.doSubmitEdit()
      return true
    },
    doCancelEdit() {
      this.visible = false
      this.$emit('close')
      this.$emit('refresh')
    },
    openChangeHistoryDialog(historyList) {
      /** 打开详情对话框实现*/
      this.$refs[historyList].visible = true
    },
    // 执行策划保存操作后，保存里程碑信息
    afterSubmit() {
      if (this.model.firstAdd !== 1) {
        this.$refs.line.updateInfo().then(() => {
          this.$refs.line.milepostLoadInfo()
        }).catch(res => {
          this.$tap.alert(res.message, 'warning')
        })
      }
    }
  },
  created() {
    window.addEventListener('resize', this.resizeHandler)
  }
}
</script>
<style scoped lang="scss">
/deep/.el-drawer {
  padding: 0 15px;
}
/deep/ .el-drawer__body {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  flex: 1;
  overflow: auto;
  border-top: 1px solid rgb(232, 232, 232);
}
</style>
